package org.basis.netty.chat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.basis.netty.chat.protocol.MessageCodecSharable;
import org.basis.netty.chat.protocol.ProcotolFrameDecoder;
import org.basis.netty.chat.server.handler.*;

/**
 * 聊天室server端
 *
 * @author Mr_wenpan@163.com 2021/09/23 10:47
 */
@Slf4j
public class ChatServer {

    public static void main(String[] args) {

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        // 抽取可在多个线程共享的handler（公用）
        final MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.INFO);
        final LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        final ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        final GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        final GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        final GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();
        final GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        final GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        final QuitHandler QUIT_HANDLER = new QuitHandler();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            // 客户端连接建立后为客户端channel添加handler
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // 添加自定义的协议的预设长度解码器，按自定义规则解码从socket中读取的消息
                    pipeline.addLast(new ProcotolFrameDecoder());
                    pipeline.addLast(LOGGING_HANDLER);
                    // 使用自定义协议对消息进行编码解码，在这个handler后面的handler接收到的数据就是这里解码后的数据了
                    pipeline.addLast(MESSAGE_CODEC);

                    // 客户端心跳检查handler
                    // 用来判断是不是 读空闲时间过长，或 写空闲时间过长
                    // 5s 内如果没有收到 channel 的数据，会触发一个 IdleState#READER_IDLE 事件
                    pipeline.addLast(new IdleStateHandler(5000, 0, 0));
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    pipeline.addLast(new ChannelDuplexHandler() {
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了读空闲事件
                            if (event.state() == IdleState.READER_IDLE) {
                                log.info("已经 5s 没有读取到客户端数据了");
                                // 关闭和客户端通信的channel
                                ctx.channel().close();
                            }
                        }
                    });

                    // 每一个handler处理的消息类型不同
                    pipeline.addLast(LOGIN_HANDLER);
                    pipeline.addLast(CHAT_HANDLER);
                    pipeline.addLast(GROUP_CREATE_HANDLER);
                    pipeline.addLast(GROUP_JOIN_HANDLER);
                    pipeline.addLast(GROUP_MEMBERS_HANDLER);
                    pipeline.addLast(GROUP_QUIT_HANDLER);
                    pipeline.addLast(GROUP_CHAT_HANDLER);
                    pipeline.addLast(QUIT_HANDLER);
                }
            });

            // 阻塞等待server关机
            ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception ex) {
            log.error("server error ", ex);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }
}
